package com.liuning.graduationdemo.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuning.graduationdemo.entity.User;
import com.liuning.graduationdemo.service.IDoctorService;
import com.liuning.graduationdemo.utils.TokenUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.liuning.graduationdemo.service.IOrderService;
import com.liuning.graduationdemo.entity.Order;
import org.springframework.web.bind.annotation.RequestMapping;
import com.liuning.graduationdemo.common.Result;
import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pumpkin
 * @since 2022-04-25
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private IOrderService orderService;

    @Resource
    private IDoctorService doctorService;

    /**
     * 保存或更新
     * @param order
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Order order) {
        return Result.success(orderService.saveOrUpdate(order));
    }

    @GetMapping("/booking/{doctorId}/{doctorName}/{bookingPrice}")
    @Transactional
    public Result booking(@PathVariable(name = "doctorId") Integer doctorId,
                          @PathVariable(name = "doctorName") String doctorName,
                          @PathVariable(name = "bookingPrice")BigDecimal bookingPrice) {

        System.out.println(doctorId + "=" + doctorName + "=" + bookingPrice);

        String subjectTitle = "预约挂号";
        String orderNo = IdUtil.getSnowflake(1,1).nextIdStr();
        String payUrl = "http://localhost:8085/alipay/pay?subject=" + subjectTitle + "&traceNo=" + orderNo + "&totalAmount=" + bookingPrice;
        System.out.println("生产订单的url：" + payUrl);

        User currentUser = TokenUtils.getCurrentUser();

        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setTotalPrice(bookingPrice);
        order.setPayPrice(bookingPrice);
        order.setName(subjectTitle);
        order.setDoctorId(doctorId);
        order.setDoctorName(doctorName);
        order.setTransportPrice(BigDecimal.ZERO);
        order.setUserId(currentUser.getId());
        order.setUsername(currentUser.getNickname());
        //进行保存
        save(order);

        // 同步修改对应doctor的剩余可预约数量
        int res = doctorService.updateBookingNumberById(doctorId);
        System.out.println(res);
        if (res > 0) {
            return Result.success(payUrl);
        }else {
            return Result.error();
        }
    }

    /**
     * 重新支付未支付的挂号
     * @param doctorId
     * @param doctorName
     * @param bookingPrice
     * @return
     */
    @GetMapping("/retryPay/{orderId}")
    @Transactional
    public Result retryPay(@PathVariable(name = "orderId") Integer orderId) {

        System.out.println(orderId + "=" + orderId);

        //先根据传入的orderId查找order表中的订单信息
        Order retryOrder = orderService.getById(orderId);
        System.out.println("数据库获取到的order信息：" + retryOrder.toString());

        String orderNo = IdUtil.getSnowflake(1,1).nextIdStr();
        String payUrl = "http://localhost:8085/alipay/pay?subject=" + retryOrder.getName() + "&traceNo=" + retryOrder.getOrderNo() + "&totalAmount=" + retryOrder.getTotalPrice();
        System.out.println("重试订单的url：" + payUrl);

        User currentUser = TokenUtils.getCurrentUser();

        return Result.success(payUrl);
    }

    /**
     * 删除单条数据
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        orderService.removeById(id);
        return Result.success();
    }

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping
    public Result findAll() {
        return Result.success(orderService.list());
    }

    /**
     * 根据id查询一条数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(orderService.getById(id));
    }

    /**
     * 分页查找所有数据
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",0);
        queryWrapper.eq("user_id",TokenUtils.getCurrentUser().getId());
        queryWrapper.orderByDesc("id");
        return Result.success(orderService.page(new Page<>(pageNum, pageSize),queryWrapper));
    }

    @GetMapping("/patientPage")
    public Result findPatientPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String nickname) {

        return Result.success(orderService.findPatientPage(new Page<>(pageNum, pageSize),nickname));
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        orderService.removeBatchByIds(ids);
        return Result.success();
    }


}

